package echo.service.impl;

import echo.exception.BusinessException;
import echo.service.IOrderService;
import echo.service.OrderRepository;
import echo.vo.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class OrderServiceImp implements IOrderService {
    private OrderRepository orderRepository;
    private ItemService itemService;
    private ItemModification itemModification;
    public OrderServiceImp(OrderRepository orderRepository, ModificationType modifyType) {
        this.orderRepository = orderRepository;
    }

    @Override
    public Order modifyOrder(String orderId, ModificationRequest request) {
        Order order=orderRepository.findById(request.getOrderId());
         if (order==null){
             throw new BusinessException(BusinessException.ErrorTyle.ORDER_NOT_FOUND);
         }
         if (order.getStatus()== OrderStatus.PAID || order.getStatus()==OrderStatus.UNPAID){
             throw new BusinessException(BusinessException.ErrorTyle.MODIFY_FORBIDDEN);
         }
        // 3. 处理不同类型的修改
        switch (request.getModificationType()) {
            case FULL_ORDER_REPLACE:
                // 处理整单替换逻辑
               order.setItems(request.getNewItems());
                break;
            case PARTIAL_MODIFICATION:
                        // 部分修改
               for (ItemModification itemModification : request.getItemModifications()) {
                   switch (itemModification.getAction()) {
               case "ADD_ITEM":
                   // 添加商品
                   order.getItems().add(itemModification.getItem());//从订单里获取商品添加到需要修改的商品里去
                   break;
               case "REMOVE_ITEM":
                   // 删除商品
                   order.getItems().removeIf(item -> item.getId().equals(itemModification.getItemId()));
                   break;
               case "MODIFY_QUANTITY":
                   // 修改数量
                   for (Item item : order.getItems()) {
                       if (item.getId().equals(itemModification.getItemId())) {
                           item.setQuantity(itemModification.getQuantity());
                           break;
                       }
                   }
                   break;
                       default:
                           throw new BusinessException(BusinessException.ErrorTyle.UNKNOWN_MODIFICATION_ACTION);
                   }
                        break;
                }

                // 保存订单
                orderRepository.save(order);
                handlePartialModification(order, request);
                break;
            default:
                throw new BusinessException(BusinessException.ErrorTyle.Invalid_MODIFY_TYPE);
        }
        return null;
    }

    @Override
    public void handlePartialModification(Order order, ModificationRequest request) {
        if (order == null) {
            throw new BusinessException(BusinessException.ErrorTyle.ORDER_NOT_FOUND);
        }

        // 检查商品有效性
//        List<Item> itemsToCheck = request.getNewItems() != null ? request.getNewItems() :
//                request.getItemModifications().stream()
//                        .map(mod -> mod.getItem())
//                        .filter(Objects::nonNull)
//                        .collect(Collectors.toList());
//        for (Item item : itemsToCheck) {
//            if (!itemService.isItemValid(item.getId())) {
//                throw new BusinessException(BusinessException.ErrorTyle.ITEM_INVALID);
//            }
//        }



        // 生成修改差异单
        ModificationDiff diff = generateModificationDiff(order, request);

        // 商家审批
        if (!merchantApproval(diff)) {
            logOperation("Approval failed", diff);
            return;
        }

        // 修改订单状态
        order.setStatus(OrderStatus.MODIFIED);

        // 执行修改
        applyModifications(order, request);

        // 生成操作日志
        logOperation("Order modified", diff);

        // 保存订单
        orderRepository.save(order);
    }


    private ModificationDiff generateModificationDiff(Order order, ModificationRequest request) {
        // 生成修改差异单的逻辑
        return new ModificationDiff(order.getItems(), request.getNewItems(), request.getItemModifications());
    }

    private boolean merchantApproval(ModificationDiff diff) {
        // 商家审批逻辑
        return true; // 假设审批通过
    }

    private void applyModifications(Order order, ModificationRequest request) {
        // 执行具体修改操作的逻辑
        switch (request.getModificationType()) {
            case FULL_ORDER_REPLACE:
                order.setItems(request.getNewItems());
                break;
            case PARTIAL_MODIFICATION:
                for (ItemModification itemModification : request.getItemModifications()) {
                    switch (itemModification.getAction()) {
                        case "ADD_ITEM":
                            order.getItems().add(itemModification.getItem());
                            break;
                        case "REMOVE_ITEM":
                            order.getItems().removeIf(item -> item.getId().equals(itemModification.getItemId()));
                            break;
                        case "MODIFY_QUANTITY":
                            for (Item item : order.getItems()) {
                                if (item.getId().equals(itemModification.getItemId())) {
                                    item.setQuantity(itemModification.getQuantity());
                                    break;
                                }
                            }
                            break;
                    }
                }
                break;
        }
    }

    private void logOperation(String message, ModificationDiff diff) {
        // 记录操作日志的逻辑
        System.out.println(message + ": " + diff);
    }
}


